/*
 * Copyright 1999,2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.webduff.methods;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.googlecode.webduff.WebdavStatus;
import com.googlecode.webduff.exceptions.AccessDeniedException;
import com.googlecode.webduff.exceptions.MethodResponseError;
import com.googlecode.webduff.exceptions.ObjectAlreadyExistsException;
import com.googlecode.webduff.exceptions.WebdavException;
import com.googlecode.webduff.io.URI;
import com.googlecode.webduff.locking.AcquiredLock;
import com.googlecode.webduff.locking.LockFailedException;
import com.googlecode.webduff.locking.ResourceLocks;

import java.io.IOException;

public class DoHead extends AbstractMethod {
	
	@SuppressWarnings("unused")
	private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(DoHead.class);

	public MethodResponse execute(HttpServletRequest req, HttpServletResponse resp) throws IOException, MethodResponseError {
		URI theURI = getURIForRequest(req);
		MethodResponse theResponse = null;
		boolean bUriExists = store.isFolder(theURI) || store.objectExists(theURI);
		
        AcquiredLock acquiredLock = null;
        
        try {
			acquiredLock = acquireSharedLock(theURI, ResourceLocks.FLAT, req);
		} catch (LockFailedException e) {
			throw new MethodResponseError(WebdavStatus.SC_LOCKED);
		}
		
		try {
			if (store.isResource(theURI)) {
				theResponse = new MethodResponse(resp);
				
				// path points to a file but ends with / or \
				if (theURI.getPath().endsWith("/") || (theURI.getPath().endsWith("\\"))) {
					throw new MethodResponseError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
				} else {
					// setting headers
					long lastModified = store.getLastModified(theURI).getTime();
					theResponse.setDateHeader("last-modified", lastModified);
					long resourceLength = store.getResourceLength(theURI);

					if (resourceLength > 0) {
						if (resourceLength <= Integer.MAX_VALUE) {
							theResponse.setContentLength(resourceLength);
						} else {
							theResponse.setHeader("content-length", Long.toString(resourceLength));
						}
					}

					String mimeType = theMimeTyper.getMimeType(theURI);
					String path = theURI.getPath();
					if (mimeType != null) {
						theResponse.setContentType(mimeType);
					} else {
						int lastSlash = path.replace('\\', '/').lastIndexOf('/');
						int lastDot = path.indexOf(".", lastSlash);
						if (lastDot == -1) {
							theResponse.setContentType("text/html");
						}
					}
					doBody(new URI(path), theResponse);
				}
			} else {
				folderBody(theURI, req, resp);
			}
		} catch (AccessDeniedException e) {
			throw new MethodResponseError(WebdavStatus.SC_FORBIDDEN);
		} catch (ObjectAlreadyExistsException e) {
			throw new MethodResponseError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
		} catch (WebdavException e) {
			throw new MethodResponseError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
		} catch (ServletException e) {
			throw new WebdavException(e);
		} finally {
			acquiredLock.unlock();
		}
		
		if (!bUriExists) {
			theResponse.setStatusCode(WebdavStatus.SC_NOT_FOUND);
		}
		
		return theResponse;
	}

	protected void folderBody(URI uri, HttpServletRequest req, HttpServletResponse resp) throws IOException, MethodResponseError, ServletException {
		// no body for HEAD
	}

	protected void doBody(URI uri, MethodResponse response)throws IOException {
		// no body for HEAD
	}
	
}